var core = require('core');
/* GET home page. */

var getRegion = function(req, res, next) {
    var q = req.query.p ? req.query : req.body;
    var query = {};
    var SEND;
    if(q.p == 0 || q.p){
        if(typeof parseInt(q.p) === "number")
            query.value = q.p;
        else
            query.label = q.p;
    };
    core.db.schema.Region.find(query, "-_id -__v -children._id -children.children._id", function(err, doc){
        if(err)
            return function(){
                console.error(err);
                SEND = new core.send(100000);
                res.send(SEND);
            }()

        var city,area;
        if((q.p == 0 || q.p) && (q.c == 0 || q.c)){
            if(parseInt(q.c) == 0 || parseInt(q.c))
                city = {
                    type: "value",
                    value: q.c
                };
            else
                city = {
                    type: "label",
                    value: q.c
                };
            for(var i = 0; i < doc[0].children.length; i++){
                // console.log(i,'==city======',city.type,'===',city.value,'===',city.value == doc.children[i][city.type]);
                if(doc[0].children[i][city.type] == city.value){
                    doc[0].children = doc[0].children[i];
                    break;
                }
            };
        }
        if((q.p == 0 || q.p) && (q.c == 0 || q.c) && (q.a == 0 || q.a)){
            if(parseInt(q.a) == 0 || parseInt(q.a))
                area = {
                    type: "value",
                    value: q.a
                };
            else
                area = {
                    type: "label",
                    value: q.a
                };



            for(var i = 0; i < doc[0].children[0].children.length; i++){
                if(doc[0].children[0].children[i][area.type] == area.value){
                    doc[0].children[0].children = doc[0].children[0].children[i];
                    break;
                }
            }
        };
        SEND = new core.send(0);
        SEND.docs = doc;

        res.send(SEND);
    });
}

module.exports = getRegion;
